package yl.hs.bmipfull.service.system.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import yl.hs.bmipfull.daos.system.IImageInfoDao;
import yl.hs.bmipfull.pojo.system.ImageInfoEntity;
import yl.hs.bmipfull.service.system.IImageInfoService;
import yl.hs.bmipfull.utils.FileUtil;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 作用:  图片信息服务层接口实现<br/>
 * 创建时间: 2021年05月13日 11时55分15秒 <br/>
 *
 * @author 张凯
 */
@Service
public class ImageInfoServiceImpl extends SystemBaseService implements IImageInfoService {

    @Autowired
    IImageInfoDao dao;

    @Override
    public List<ImageInfoEntity> queryAll() {
        return dao.queryAll();
    }

    @Override
    public File findBySn(String sn) throws IOException {
        ImageInfoEntity imageInfoEntity = dao.findBySN(sn);

        return FileUtil.loadFile("" + imageInfoEntity.getFilename());
    }

    @Override
    public String saveImageInfo(MultipartFile file) throws Exception {
        Integer result = 0;
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
        int index = originalFilename.lastIndexOf(".");

        String filename = UUID.randomUUID() + ".hsxx";
        String path = System.getProperty("user.dir");
        ImageInfoEntity imageInfoEntity = null;
        String filePath = path.substring(0, path.lastIndexOf(  File.separator)) + File.separator + "bmiImage";
        if (FileUtil.upload(filePath, filename, file)) {
            imageInfoEntity = new ImageInfoEntity();
            imageInfoEntity.setFilename(filePath +   File.separator + filename);
            imageInfoEntity.setOriginalFilename(originalFilename);
            imageInfoEntity.setSn(queryNewSN(imageInfoEntity.getClass()));
            result = dao.insertNew(imageInfoEntity);
        }
        return imageInfoEntity != null ? imageInfoEntity.getSn() : "";
    }

    @Override
    public Integer delete(String sn) {
        Integer result = 0;
        File file = null;
        try {
            file = findBySn(sn);
            file.delete();
            result++;
        } catch (IOException e) {
            e.printStackTrace();
        }


        return result;
    }
}